<template>
    <view class="canvas-container">
        <canvas canvas-id="myCanvas" :style="{ width: '100%', height: '100vh' }"></canvas>
    </view>
</template>

<script>
import { onMounted, ref } from 'vue'
import { fabric } from 'fabric'

export default {
    setup() {
        const canvas = ref(null)
        const fabricCanvas = ref(null)

        onMounted(() => {
            // 获取canvas DOM元素
            canvas.value = uni.createCanvasContext('myCanvas')

            // 初始化Fabric画布
            fabricCanvas.value = new fabric.Canvas('myCanvas')

            // 设置画笔颜色和粗细
            fabricCanvas.value.freeDrawingBrush.color = 'black' // 默认颜色为黑色
            fabricCanvas.value.freeDrawingBrush.width = 2 // 默认线条粗细为2

            // 添加画笔事件监听
            fabricCanvas.value.on('mouse:down', onMouseDown)
            fabricCanvas.value.on('mouse:move', onMouseMove)
            fabricCanvas.value.on('mouse:up', onMouseUp)

            function onMouseDown(options) {
                fabricCanvas.value.freeDrawingBrush.start(options)
            }

            function onMouseMove(options) {
                fabricCanvas.value.freeDrawingBrush.move(options)
            }

            function onMouseUp(options) {
                fabricCanvas.value.freeDrawingBrush.end(options)
            }
        })

        // 暴露方法以调整画笔颜色和粗细
        const setColor = (color) => {
            fabricCanvas.value.freeDrawingBrush.color = color
        }

        const setWidth = (width) => {
            fabricCanvas.value.freeDrawingBrush.width = width
        }

        return {
            setColor,
            setWidth,
        }
    },
}
</script>

<style scoped>
.canvas-container {
    width: 100%;
    height: 100%;
}
</style>